package gateway.rule.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import gateway.api.annotation.Named;
import gateway.api.engine.Chain;
import gateway.api.engine.Filter;
import gateway.api.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author Jin Zheng
 * @since 1.0 2020-09-21
 */
@Named(value = "jsonPathFilter", async = false)
public class JsonPathFilter implements Filter
{
	private static Logger logger = LoggerFactory.getLogger(JsonPathFilter.class);
	public static final String EXPRESSION = "expression";
	public static final String EQUAL = "=";

	private Map<String, String> args;

	public JsonPathFilter()
	{
	}

	@Override
	public void handle(Message message, Chain chain)
	{
		String expression = args.get(EXPRESSION);
		logger.debug("expression: {}", expression);
		if (expression == null || expression.isEmpty() || !expression.contains(EQUAL))
		{
			chain.doNext();
			return;
		}

		this.match(message.body(), expression, chain);
	}

	private void match(String body, String expression, Chain chain)
	{
		String[] exp = expression.split(EQUAL);
		JSONObject json = JSON.parseObject(body);
		Object value = JSONPath.eval(json, exp[0]);
		if (value == null && exp[1].isEmpty())
		{
			chain.doNext();
			return;
		}
		if (value != null && value.toString().equals(exp[1]))
		{
			chain.doNext();
		}

	}

	@Override
	public void setArgs(Map<String, String> args)
	{
		this.args = args;
	}
}
